<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 公司荣誉统计编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="项目基本信息"></title-name>
          <custom-form
            @getOption="getOption"
            :formList="formList"
            :form="form"
            :editModel="editModel == 0 ? 'V' : ''"
          >
            <!-- 附件上传 -->
            <template #fileList>
              <template v-if="editModel != 0">
                <l-table
                  businessCode="OF02"
                  :uploadArrys.sync="form.fileList"
                ></l-table>
                <div class="file_prompt">
                  请上传荣誉扫描件或其他电子版原件，支持格式：.rar .zip .doc .docx .pdf .jpg .png .mp4 .mov
                </div>
              </template>
              <file-link
                v-else
                :fileList="form.fileList"
                style="margin-top: -3px"
              ></file-link>
            </template>
            <template #awardWinningUnit>
              <span v-if="editModel == 0">{{ form.awardWinningUnitName }}</span>
              <org-tree-select 
                v-else
                v-model="form.awardWinningUnit"
                @select="selectOrg"
              />
            </template>
          </custom-form>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button
          :loading="loading"
          v-if="editModel != 0"
          type="primary"
          class="button_right"
          @click="handleSubmit"
        >提交</a-button>
        <a-button
          type="primary"
          @click="handleActiveClose"
        >关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { enterpriseHonor } from '@/api/office/office/enterpriseHonorAndImgCollect' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import Selector from '@/components/Select/Selector'
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople' // 班主
import { mapGetters } from 'vuex'

export default {
  extends: new BaseEditPage(),
  data() {
    return {
      loading: false, // 加载控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {}, // 表单
      rules: {
        name: [{ required: true, whitespace: true, message: '请输入荣誉名称', trigger: 'change' }],
        levelId: [{ required: true, message: '请选择荣誉级别', trigger: 'change' }],
        formId: [{ required: true, message: '请选择形式', trigger: 'change' }],
        otherForm: [{ required: true, message: '请选择其他形式', trigger: 'change' }],
        awardTime: [{ required: true, message: '请选择获奖时间', trigger: 'change' }],
        subjectId: [{ required: true, message: '请选择获奖主体', trigger: 'change' }],
        awardWinningUnit: [{ required: true, message: '请选择获奖人员或获奖单位', trigger: 'change' }],
        awardUnit: [{ required: true, message: '请输入颁发单位 ', trigger: 'change' }],
        isTransfer: [{ required: true, message: '请选择是否移交归档', trigger: 'change' }],
        fileList: [{ type: 'array', required: true, message: '请上传文件', trigger: 'blur' }]
      }, // 校验规则
      init: false, // 初始化控件
      formCode: '', // 形式选中项code
      subjectCode: '' // 获奖主体选中项code
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileList'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileList')
        })
      }
    },
    // 监听形式
    'form.formId'(e) {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          if (this.form.otherForm) {
            this.form.otherForm = ''
          } else {
            this.$set(this.form, 'otherForm', '')
          }
        })
      }
    },
    // 监听获奖主体
    'form.subjectId'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          if (this.form.awardWinningUnit) {
            this.form.awardWinningUnit = this.subjectCode == 1 ? [] : void 0
            this.form.awardWinningUnitName = ''
          } else {
            this.$set(this.form, 'awardWinningUnit', this.subjectCode == 1 ? [] : void 0)
            this.$set(this.form, 'awardWinningUnitName', '')
          }
        })
      }
    }
  },
  mounted() {
    this.$route.meta.title = ['公司荣誉统计查看', '公司荣誉统计编辑', '公司荣誉统计新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      enterpriseHonor
        .detail(this.id)
        .then((res) => {
          this.loading = false
          res.data.isTransferName = res.data.isTransfer ? '是' : '否'
          this.formCode = res.data.formCode
          this.subjectCode = res.data.subjectCode
          if (this.editModel == 1) {
            if (this.subjectCode == 1) {
              let awardWinningUnit = res.data.awardWinningUnit.split(',')
              let awardWinningUnitName = res.data.awardWinningUnitName.split(',')
              res.data.awardWinningUnit = awardWinningUnit.map((item, index) => {
                return {
                  key: item,
                  label: awardWinningUnitName[index]
                }
              })
            } else {
              res.data.awardWinningUnit = res.data.awardWinningUnit
              res.data.awardWinningUnitName = res.data.awardWinningUnitName
            }
          }
          console.log(this.subjectCode == 1)
          console.log( res.data)
          this.form = res.data
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.$nextTick(() => {
        this.init = true
      })
    }
  },
  computed: {
    ...mapGetters(['nickname', 'avatar']),
    formList() {
      return [
        {
          keyName: 'name',
          type: 'BaseInput',
          label: '荣誉名称'
        },
        {
          keyName: 'levelId',
          viewName: 'levelName',
          label: '荣誉级别',
          type: Selector,
          attrs: {
            selectType: '1',
            urlType: 'office'
          }
        },
        {
          keyName: 'formId',
          viewName: 'formName',
          label: '形式',
          type: Selector,
          attrs: {
            selectType: '2',
            urlType: 'office'
          }
        },
        {
          keyName: 'otherForm',
          hidden: this.formCode != '5',
          type: 'a-input',
          label: '其他形式'
        },
        {
          keyName: 'awardTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '获奖时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'subjectId',
          viewName: 'subjectName',
          label: '获奖主体',
          type: Selector,
          attrs: {
            selectType: '10',
            urlType: 'office'
          }
        },
        {
          keyName: 'awardWinningUnit',
          viewName: 'awardWinningUnitName',
          hidden: this.subjectCode !== '1',
          label: '获奖人员',
          placeholder: '请选择获奖人员',
          type: ASelectOrgPeople,
          attrs: {
            mode: 'multiple',
            labelInValue: true,
            customRender(i) {
              return `${i.name}-${i.phoneNum}`
            }
          }
        },
        {
          // keyName: 'awardWinningUnit',
          hidden: this.subjectCode !== '0',
          // viewName: 'awardWinningUnitName',
          // placeholder: '请选择获奖单位',
          // type: 'orgTree',
          // label: '获奖单位',
          // slot: this.editModel==0,
          slot: true,
          keyName: 'awardWinningUnit',
          label: '获奖单位',
        },
        {
          keyName: 'awardUnit',
          type: 'BaseInput',
          label: '授奖单位'
        },
        {
          keyName: 'number',
          hidden: this.formCode != '5' && this.formCode != '3',
          type: 'BaseInput',
          label: '文号/荣誉编号'
        },
        {
          keyName: 'isTransfer',
          viewName: 'isTransferName',
          type: 'a-select',
          label: '是否移交归档',
          data: [
            {
              label: '否',
              value: 0
            },
            {
              label: '是',
              value: 1
            }
          ]
        },
        {
          slot: true,
          keyName: 'fileList',
          label: '附件',
          span: 24
        }
      ]
    }
  },
  methods: {
    /**
     * 获取选中项code
     */
    getOption(name, e) {
      if (e) {
        // 获取形式code
        if (name === 'formId') {
          this.formCode = e.code
          // 获取获奖主体code
        } else if (name === 'subjectId') {
          this.subjectCode = e.code
        }
      }
    },
    /**
     * @description: 获奖单位改变时获取名称
     * @param {array} val
     * @return {void}
     */    
    selectOrg(val){
      console.log(val)
      this.form.awardWinningUnitName =  val.map(el=>{
        return el?.projectName || el.orgName
      }).join('/')
    },
    /**
     * 提交表单
     */
    handleSubmit() {

      let api = ['update', 'create'][this.editModel - 1] // 根据操作切换url地址
      // 校验表单
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          try {
            // 提交表单
          this.loading = true
          const {
            name,
            levelId,
            formId,
            otherForm,
            awardTime,
            subjectId,
            awardWinningUnit,
            awardWinningUnitName,
            awardUnit,
            isTransfer,
            fileList
          } = this.form
          const form = {
            name,
            levelId,
            formId,
            otherForm,
            awardTime,
            subjectId,
            awardUnit,
            isTransfer,
            fileList
          }
          if (this.subjectCode == 0) {
            form.awardWinningUnitName = awardWinningUnitName
            form.awardWinningUnit = awardWinningUnit
          } else {
            form.awardWinningUnitName = awardWinningUnit.map(el=>{
              const list = el.label[0]?.componentOptions?.children
              return list[list.length-1]?.children[0]?.text
            }).join(',')
            form.awardWinningUnit = awardWinningUnit.map((item) => item.key).join(',')
          }
          if(this.editModel == 1){
            form.id= this.$route.query.id
          }
          enterpriseHonor[api](form)
            .then(() => {
              this.loading = false
              this.$message.success('提交成功！')
              this.$multiTab.close()
            })
            .catch(() => {
              this.loading = false
            })
          } catch (error) {
            console.log(error)
          }
          
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-form-item {
  .ant-form-item-label {
    height: 28px;
    width: 200px;
    line-height: 22px;
    padding: 6px 4px 0 0;
    text-align: right;
    white-space: pre-wrap;
    overflow: visible;
  }
  .ant-form-item-control-wrapper {
    width: calc(100% - 200px);
  }
}
.file_prompt {
  color: #999;
}
</style>
